package com.heima.sjms.单例.单例被破坏;

import java.io.*;

/**
 * 单例：多次操作，使用的是同一个对象
 *
 * static: 被static修饰的成员属于类，被该类的所有对象共享使用
 *  final: 最终态
 */

public class Student implements Serializable {
}


class Demo{
    private static Student stu;

    public static void main(String[] args) throws Exception {
        Student t1 = getStu();
        System.out.println("t1 = " + t1);

        //基于反射破坏单例
        Class clazz = t1.getClass();
        Student t2 = (Student) clazz.newInstance();
        System.out.println("t2 = " + t2);

        //基于序列化方式来破坏
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D://a.txt"));
        oos.writeObject(t1);
        oos.close();

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D://a.txt"));
        Student t3 = (Student) ois.readObject();
        ois.close();
        System.out.println("t3 = " + t3);

    }

    //懒汉式：不用不创建，用的时候再创建
    //双检锁
    public static Student getStu(){
        synchronized ("abc") {
            if (stu == null){
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                stu = new Student();
            }
        }
        return stu;
    }

}
